<template>
  <q-modal v-model="modalVisible" :header="`${$t('Misc.SpecifyDetails', { name: 'AGV' })}`" :menuBtn="false"
           :persistent="false" classes="row" width="65%">
    <div class="row q-gutter-md">
      <div class="col-xs-12 col-sm-6 col-md-4 row justify-center">
        <div class="col-6 row justify-between">
          <q-chip :color="formatColor(rowInfo.isLease)" class="no-margin q-pa-xs text-caption" dense square
                  text-color="white">
            {{ rowInfo.isLease === '1' ? $t('Misc.Rent') : $t('Misc.Buy') }}
          </q-chip>
          <q-chip :color="formatColor(rowInfo.grade || 'A')" class="clip-chip-tri no-margin" dense square
                  text-color="white">
            {{ rowInfo.grade || 'A' }}
          </q-chip>
          <div class="full-width row justify-center q-pa-sm">
            <AMRIMG :amrType="rowInfo.agvTypeCode" :imageUrl="rowInfo.imageUrl"
                    classes="col-8 rounded-borders"></AMRIMG>
          </div>
          <div class="full-width row no-wrap justify-between items-center q-gutter-x-xs">
            <q-icon class="rotate-90 no-margin" size="2rem" v-bind="batteryAttrs"></q-icon>
            <span v-if="tpmInfo.battery">{{ tpmInfo.battery || 0 }}%</span>
            <span v-else class="text-grey-6 q-pt-xs text-caption">{{ $t('Misc.Uncounted') }}</span>
            <q-space></q-space>
            <q-badge :color="formatColor(tpmInfo.agvStatus)" class="q-badge-dot" rounded></q-badge>
            <span class="text-grey-6">{{ getLabelByValue(tpmInfo.agvStatus, statusOptions) }}</span>
          </div>
        </div>
        <template v-for="col in runningColumns" :key="col.field">
          <q-item
            class="col-12 text-subtitle1 line-height-1 rounded-borders bg-grey-2 items-center q-mx-auto q-py-sm q-px-md">
            <q-avatar :icon="col.icon" class="on-left" font-size="1rem" size="1.5rem" text-color="deep-purple-7" />
            {{ col.label }}
          </q-item>
          <q-item v-if="col.children?.length" class="col-12 q-mx-auto">
            <q-item-section v-for="child in col.children" :key="child.field">
              <q-item-label class="text-grey-6 text-body2">{{ child.label }}</q-item-label>
              <q-item-label class="text-weight-medium">
                {{ formatLabel(child, cumulativeInfo, $t('Misc.Uncounted')) }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </template>
      </div>
      <div class="col column justify-between no-wrap rounded-borders q-pa-md bg-grey-2">
        <q-item class="text-subtitle1 line-height-1 no-padding items-center">
          <q-avatar class="on-left" font-size="1rem" icon="mdi-cog-outline" size="1.5rem" text-color="deep-purple-7" />
          {{ $t('SystemCore.BasicInformation') }}
        </q-item>
        <q-item v-for="col in basicColumns" :key="col.field" class="q-py-xs q-px-sm">
          <q-item-section class="col-auto text-grey-6 text-body2">{{ col.label }}:</q-item-section>
          <q-item-section class="text-weight-medium">{{ formatLabel(col, basicInfo) }}</q-item-section>
        </q-item>
        <q-item class="q-py-xs q-px-sm">
          <q-item-section class="col-auto text-grey-6 text-body2">{{ $t('AGVCore.NavigationType') }}:</q-item-section>
          <q-item-section>
            <div class="row no-wrap items-center q-gutter-sm text-body1">
              <q-icon :color="basicInfo.navigationType === '0' ? 'primary' : 'grey-5'" name="qr_code"></q-icon>
              <q-icon :color="basicInfo.navigationType === '3' ? 'primary' : 'grey-5'" name="view_in_ar"></q-icon>
              <q-icon :color="basicInfo.navigationType === '4' ? 'primary' : 'grey-5'" class="rotate-135"
                      name="straighten"></q-icon>
              <q-icon :color="basicInfo.navigationType === '1' ? 'primary' : 'grey-5'" name="flare"></q-icon>
              <div :class="basicInfo.navigationType === '2' ? 'text-primary' : 'text-grey-5'" class="text-no-wrap">
                slam
              </div>
            </div>
          </q-item-section>
        </q-item>
      </div>
      <div class="col-xs-12 col-sm-6 col-md-5 column justify-between">
        <div v-for="col in miscColumns" :key="col.field" class="full-width">
          <q-item class="col-12 text-subtitle1 line-height-1 rounded-borders bg-grey-2 items-center q-py-sm q-px-md">
            <q-avatar :icon="col.icon" class="on-left" font-size="1rem" size="1.5rem" text-color="deep-purple-7" />
            {{ col.label }}
          </q-item>
          <div v-if="col.children?.length" class="col-12 row q-py-sm q-px-md q-col-gutter-md">
            <div v-for="child in col.children" :key="child.field" :class="child.class"
                 class="row no-wrap items-center q-gutter-sm">
              <qx-tooltip class="text-grey-6 text-body2">{{ child.label }}:</qx-tooltip>
              <qx-tooltip class="text-weight-medium">{{ formatLabel(child, tpmInfo, 'N/A') }}</qx-tooltip>
            </div>
          </div>
        </div>
      </div>
    </div>
    <q-separator class="q-my-md full-width gradient-separator-x"></q-separator>
    <PortraitCharts :leftChartData="leftChartData" :rightChartData="rightChartData"></PortraitCharts>
  </q-modal>
</template>
<script setup>
import { i18n } from 'boot/i18n.js'
import { date } from 'quasar'
import { postAPI } from 'src/api/index.js'
import AMRIMG from 'src/views/AGVCore/AMRIMG.vue'
import PortraitCharts from 'src/views/AGVCore/PortraitCharts.vue'
import { computed, ref, watchPostEffect } from 'vue'
import { AGVTypes, taskStatus } from 'src/enum/index.js'
import { getLabelByValue } from 'src/utils/utils.js'

const props = defineProps({ rowInfo: { type: Object, default: () => ({}) } })
const modalVisible = defineModel('modelValue', { type: Boolean, default: false })

const tpmInfo = ref({})
const basicInfo = ref({})
const leftChartData = ref([])
const rightChartData = ref([])
const cumulativeInfo = ref({})
const batteryAttrs = computed(() => {
  const { battery = 0 } = tpmInfo.value
  const color = battery < 20 ? 'negative' : 'positive'
  const batteryValue = Math.round(Number(battery) / 10) * 10
  if (batteryValue < 10) return { name: 'mdi-battery-outline', color }
  if (batteryValue > 90) return { name: 'mdi-battery', color }
  return { name: `mdi-battery-${batteryValue}`, color }
})
const statusOptions = computed(() => {
  return [{
    label: i18n.t('Misc.Normal'), value: 'NORMAL', color: 'primary'
  }, {
    label: i18n.t('Misc.TemporaryFix'), value: 'TEMPORARY_REPAIR', color: 'positive'
  }, {
    label: i18n.t('Misc.PostponeUse'), value: 'SUSPENDED_USER', color: 'amber-5'
  }, {
    label: i18n.t('Scrap'), value: 'SCRAP', color: 'red'
  }]
})
const runningColumns = computed(() => {
  return [{
    label: i18n.t('Misc.TotalRunningStats'), field: 'TotalRunningStats', icon: 'bubble_chart', children: [{
      label: i18n.t('Misc.DaysSinceEntry'), field: 'sumDays', unit: i18n.t('Day')
    }, {
      label: i18n.t('Misc.RunningMileage'), field: 'sumDistance', unit: 'Km'
    }, {
      label: i18n.t('Misc.RunningDuration'), field: 'sumHours'
    }]
  }, {
    label: i18n.t('Misc.LocalRunningStats'), field: 'LocalRunningStats', icon: 'stacked_bar_chart', children: [{
      label: i18n.t('Misc.DaysSinceEntry'), field: 'sumFactoryDays', unit: i18n.t('Day')
    }, {
      label: i18n.t('Misc.RunningMileage'), field: 'sumFactoryDistance', unit: 'Km'
    }, {
      label: i18n.t('Misc.RunningDuration'), field: 'sumFactoryHours'
    }]
  }]
})
const basicColumns = computed(() => {
  return [{
    label: i18n.t('AGVCore.AGVBrand'), field: 'agvBrandName'
  }, {
    label: i18n.t('AGVCore.AGVType'), field: 'agvTypeCode', options: AGVTypes.value
  }, {
    label: i18n.t('AGVCore.AGVModel'), field: 'agvDeviceTypeName'
  }, {
    label: i18n.t('AGVCore.AGVCode'), field: 'agvDeviceCode'
  }, {
    label: i18n.t('Misc.PurchaseDate'), field: 'buyDate', format: 'YYYY-MM-DD'
  }, {
    label: i18n.t('Misc.EntryDate'), field: 'factoryDate', format: 'YYYY-MM-DD'
  }, {
    label: 'AGV IP', field: 'agvIp'
  }]
})
const miscColumns = computed(() => {
  return [{
    label: i18n.t('TaskCore.CurrentTaskInfo'), field: 'CurrentTaskInfo', icon: 'mdi-clipboard-text-multiple-outline',
    children: [{
      label: i18n.t('TaskCore.TaskCode'), field: 'taskCode', class: 'col-6'
    }, {
      label: i18n.t('TaskCore.TaskStatus'), field: 'taskStatus', class: 'col-6', options: taskStatus.value
    }, {
      label: i18n.t('TaskCore.TaskNotificationEvent'), field: 'taskCallbackEvent', class: 'col-12'
    }]
  }, {
    label: i18n.t('Misc.CurrentRunningInfo'), field: 'CurrentRunningInfo', icon: 'filter_drama', children: [{
      label: i18n.t('MapCore.Coord'), field: 'coord', class: 'col-6'
    }, {
      label: i18n.t('MapCore.LocationMap'), field: 'mapCode', class: 'col-6'
    }, {
      label: i18n.t('Misc.StatusDescription'), field: 'statusDesc', class: 'col-6'
    }]
  }, {
    label: i18n.t('Misc.CurrentAlarmInfo'), field: 'CurrentAlarmInfo', icon: 'mdi-alert-octagon-outline', children: [{
      label: i18n.t('AGVCore.AlarmCode'), field: 'originalWarnCode', class: 'col-6'
    }, {
      label: i18n.t('AGVCore.AlarmDescription'), field: 'originalWarnDesc', class: 'col-6'
    }, {
      label: i18n.t('AGVCore.AlarmCategoryCode'), field: 'originalWarnTypeCode', class: 'col-6'
    }, {
      label: i18n.t('AGVCore.AlarmCategoryDescription'), field: 'originalWarnSolution', class: 'col-6'
    }]
  }, {
    label: i18n.t('Misc.MaintenanceInfo'), field: 'MaintenanceInfo', icon: 'mdi-shield-cross-outline', children: [{
      label: i18n.t('Misc.LastMaintDate'), field: 'lastTpmDate', class: 'col-6', format: 'YYYY-MM-DD'
    }, {
      label: i18n.t('Misc.NextEstMaintDate'), field: 'expectTpmDate', class: 'col-6', format: 'YYYY-MM-DD'
    }, {
      label: i18n.t('Misc.ElapsedRunningDuration'), field: 'runDate', class: 'col-6'
    }, {
      label: i18n.t('Misc.ElapsedRunningMileage'), field: 'runDistance', class: 'col-6', unit: 'Km'
    }]
  }]
})
const formatLabel = (col, row, suffix) => {
  if (col.field === 'coord') return `${row.coordX || 0}, ${row.coordY || 0}`
  const value = row[col.field] ?? props.rowInfo[col.field]
  if (suffix) return value ? `${value}${col.unit || ''}` : suffix
  if (col.format) return value ? date.formatDate(value, col.format) : value
  if (col.options) return col.options.find(item => item.value === value)?.label || value
  return value
}
const formatColor = value => {
  if (['0', 'A'].includes(value)) return 'primary'
  if (['1', 'B'].includes(value)) return 'orange'
  if (['C'].includes(value)) return 'red'
  return statusOptions.value.find(el => el.value === value)?.color || 'primary'
}
const initData = () => {
  const { agvDeviceCode: agvCode, agvBrandCode } = props.rowInfo, month = date.formatDate(Date.now(), 'YYYY-MM')
  postAPI('/yfagv/api/monitor/getAgvBasic', { agvCode, agvBrandCode }, data => {
    basicInfo.value = data || {}
  }, () => basicInfo.value = {})
  postAPI('/yfagv/api/monitor/getAgvBasicSum', { agvCode, agvBrandCode }, data => {
    cumulativeInfo.value = data || {}
  }, () => cumulativeInfo.value = {})
  postAPI('/yfagv/api/monitor/getAgvTpm', { agvCode, agvBrandCode }, data => {
    tpmInfo.value = { ...tpmInfo.value, ...data }
  })
  postAPI('/yfagv/api/monitor/agvAggregateStatus', { agvCode, agvBrandCode }, data => {
    tpmInfo.value = { ...tpmInfo.value, ...data }
  })
  postAPI('/yfagv/api/monitor/getAgvYearInfo', { agvCode, agvBrandCode, month }, data => {
    leftChartData.value = data
  }, () => leftChartData.value = {})
  postAPI('/yfagv/api/monitor/getAgvDayInfo', { agvCode, agvBrandCode, month }, data => {
    rightChartData.value = data
  }, () => rightChartData.value = {})
}

watchPostEffect(() => modalVisible.value && initData())
</script>
<style lang="scss" scoped>
.q-avatar {
  background-color: #d3d5ff;

  .q-icon {
    color: #333fff;
    background-color: #00DFFF;
    font-size: 1.5rem;
  }
}
</style>